package com.itheima.reggie.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;


@RestControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
public class GlobalExeptionHandler {

    // 数据库的约束错误信息，可能有很多：主键 唯一 非空约束 外键约束
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handlerSQLConstraintException(SQLIntegrityConstraintViolationException exception){
        // 1、打印异常信息
        log.error(exception.getMessage());

        if(exception.getMessage().contains("Duplicate entry")){
            //获取主要异常关键字
            String[] message = exception.getMessage().split(" ");
            return R.error(message[2]+ "已存在");
        }
        return R.error("系统繁忙,请稍后再试");
    }

    //删除异常处理
    @ExceptionHandler(CustomException.class)
    public R CustomException(CustomException ce){
        log.error(ce.getMessage());
        return R.error(ce.getMessage());
    }
}
